//wx-drawer
var common = require('../../utils/common.js');
const Bmob = require("../../utils/bmob.js");
var util = require('../../utils/util.js');
var app = getApp();
var curIndex = 0;
var that;
Page({
  data: {
    dialog: false,
    autoplay: false,
    buttonClicked: false, //是否点击跳转
    //--------首页显示内容---------
    postsList: [], //总的活动
    postsShowSwiperList: [], //轮播图显示的活动
    currentPage: 0, //要跳过查询的页数
    limitPage: 3, //首先显示3条数据（之后加载时都增加3条数据，直到再次加载不够3条）
    isEmpty: false, //当前查询出来的数据是否为空
    totalCount: 0, //总活动数量
    endPage: 0, //最后一页加载多少条
    totalPage: 0, //总页数
    windowHeight1: 0,
    windowWidth1: 0,
    scrollHandle: 'scrollHandle', //scroll-view触底事件
    topNum: 0, //返回顶部
    isLogin: false, //默认不隐藏登录弹窗
    cangotop: false, //回到顶部按钮默认隐藏
    curIndex: 0
  },
  //轮播图切换图片
  onSwiperChange: function (event) {
    curIndex = event.detail.current
    this.changeCurIndex()
  },
  changeCurIndex: function () {
    this.setData({
      curIndex: curIndex
    })
  },

  onHide: function () {
    this.setData({
      autoplay: false
    })
  },
  //调用app.js onLaunch方法注册用户信息
  getUserInfo() {
    this.setData({
      isLogin: false
    })
    app.onLaunch()
  },

  onLoad(t) {

  },

  onShow: function (e) {
    wx.showNavigationBarLoading()
    this.getAll();
    this.fetchTopThreePosts(); //获取轮播图的3篇文章
    console.log('加载头像')
    var that = this
    wx.getSystemInfo({
      success: (res) => {
        this.setData({
          windowHeight1: res.windowHeight,
          windowWidth1: res.windowWidth,
          autoplay: true
        })
      }
    })
    // wx.hideLoading()
    //根据用户授权情况判断是否显示弹窗
    wx.getSetting({
      success(res) {
        if (res.authSetting['scope.userInfo']) {
          that.setData({
            isLogin: false
          })
          console.log("if getset", res)
        } else {
          that.setData({
            isLogin: true
          })
          console.log("else getset")
        }
      }
    })
  },

  //数据存储
  onSetData: function (data) {
    console.log(data.length, "data.length");
    let page = this.data.currentPage + 1;
    //设置数据
    data = data || [];
    this.setData({
      postsList: page === 1 || page === undefined ? data : this.data.postsList.concat(data),
    });
    console.log(this.data.postsList, page, "设置shuju");
  },

  //获取总的活动数
  getAll: function () {
    self = this;
    var Diary = Bmob.Object.extend("Events");
    var query = new Bmob.Query(Diary);
    query.equalTo("isShow", 1); //只统计公开显示的活动
    query.count({
      success: function (count) {
        var totalPage = 0;
        var endPage = 0;
        if (count % self.data.limitPage == 0) { //如果总数的为偶数
          totalPage = parseInt(count / self.data.limitPage);
        } else {
          var lowPage = parseInt(count / self.data.limitPage);
          endPage = count - (lowPage * self.data.limitPage);
          totalPage = lowPage + 1;
        }
        self.setData({
          totalCount: count,
          endPage: endPage,
          totalPage: totalPage
        })

        console.log("共有" + count + " 条记录");
        console.log("共有" + totalPage + "页");
        console.log("最后一页加载" + endPage + "条");
      },
    });
  },
  //最热活动，点赞数排序前三条数据
  fetchTopThreePosts: function () {
    var self = this;
    var molist = new Array();
    var Diary = Bmob.Object.extend("Events");
    var query = new Bmob.Query(Diary);
    query.equalTo("isShow", 1); //公开显示的
    query.descending("likenum");
    query.include("publisher");
    query.limit(3);
    query.find({
      success: function (results) {
        // debugger
        for (let i = 0; i < results.length; i++) {
          var publisherId = results[i].get("publisher").objectId;
          var title = results[i].get("title");
          var content = results[i].get("content");
          var acttype = results[i].get("acttype");
          var isShow = results[i].get("isShow");
          var endtime = results[i].get("endtime");
          var address = results[i].get("address");
          var addressdetail = results[i].get("addressdetail");
          var peoplenum = results[i].get("peoplenum");
          var likenum = results[i].get("likenum");
          var liker = results[i].get("liker");
          var isLike = 0;
          var commentnum = results[i].get("commentnum");
          var _url
          var actpic = results[i].get("actpic");
          var id = results[i].id;
          var createdAt = results[i].createdAt;
          var pubtime = util.getDateDiff(createdAt);
          console.log("ljp--swipe", actpic)
          if (actpic) {
            _url = results[i].get("actpic");
          } else {
            _url = "/static/images/base.png";
          }
          var publisherName = results[i].get("publisher").nickname;
          var publisherPic = results[i].get("publisher").userPic;
          var jsonA;
          jsonA = {
            "title": title || '',
            "content": content || '',
            "acttype": acttype || '',
            "isShow": isShow,
            "endtime": endtime || '',
            "address": address || '',
            "addressdetail": addressdetail || '',
            "peoplenum": peoplenum || '',
            "id": id || '',
            "publisherPic": publisherPic || '',
            "publisherName": publisherName || '',
            "publisherId": publisherId || '',
            "pubtime": pubtime || '',
            "actPic": _url || '',
            "likenum": likenum,
            "commentnum": commentnum,
            "is_liked": isLike || ''
          }
          molist.push(jsonA);
        }
        self.setData({
          postsShowSwiperList: molist
        })
        self.fetchPostsData(self.data); //加载首页信息
        wx.stopPullDownRefresh()
        wx.hideNavigationBarLoading()
      },
      error: function (error) {
        // debugger
        console.log(error, "error")
      }
    })
  },

  //获取首页列表文章
  fetchPostsData: function (data) {
    this.getScrollHeight() //获取当前页面实际高度
    var self = this;
    //获取详询活动信息
    var molist = new Array();
    var Diary = Bmob.Object.extend("Events");
    var query = new Bmob.Query(Diary);
    query.equalTo("isShow", 1); //公开显示的
    query.limit(self.data.limitPage);
    console.log(self.data.limitPage, "limitPage");
    query.skip(3 * self.data.currentPage);
    query.descending("createdAt"); //按照时间降序
    query.include("publisher");
    query.find({
      success: function (results) {
        // debugger
        for (var i = 0; i < results.length; i++) {
          var publisherId = results[i].get("publisher").objectId;
          var title = results[i].get("title");
          var content = results[i].get("content");
          var acttype = results[i].get("acttype");
          var endtime = results[i].get("endtime");
          var address = results[i].get("address");
          var acttypename = getTypeName(acttype); //根据类型id获取类型名称
          var isShow = results[i].get("isShow");
          var peoplenum = results[i].get("peoplenum");
          var likenum = results[i].get("likenum");
          var liker = results[i].get("liker");
          var isLike = 0;
          var commentnum = results[i].get("commentnum");
          var id = results[i].id;
          var createdAt = results[i].createdAt;
          var pubtime = util.getDateDiff(createdAt);
          var _url
          var actpic = results[i].get("actpic");
          console.log("ljp--shouyelist", actpic)
          // debugger
          if (actpic) {
            _url = results[i].get("actpic");
            console.log("indexlist 有进到这里来")
          } else {
            _url = "/static/images/base.png";
          }
          var publisherName = results[i].get("publisher").nickname;
          var publisherPic = results[i].get("publisher").userPic;
          var jsonA;
          jsonA = {
            "title": title || '',
            "content": content || '',
            "acttype": acttype || '',
            "acttypename": acttypename || '',
            "isShow": isShow,
            "endtime": endtime || '',
            "address": address || '',
            "peoplenum": peoplenum || '',
            "id": id || '',
            "publisherPic": publisherPic || '',
            "publisherName": publisherName || '',
            "publisherId": publisherId || '',
            "pubtime": pubtime || '',
            "actPic": _url || '',
            "likenum": likenum,
            "commentnum": commentnum,
            "is_liked": isLike || ''
          }
          molist.push(jsonA);
          console.log(jsonA, 55555)
        }
        self.onSetData(molist, self.data.currentPage);
        // wx.hideLoading()
      },
      error: function (error) {
        console.log(error, "error1")
      }
    })
  },
  scrollHandle() {
    this.loadMore()
    console.log("ljpljp")
  },
  scrollHandle1() {
    console.log("最后一页啦")
  },
  //加载下一页
  loadMore: function () {
    var self = this;
    self.setData({
      currentPage: self.data.currentPage + 1
    });
    console.log("当前页" + self.data.currentPage);
    //先判断是不是最后一页
    if (self.data.currentPage + 1 == self.data.totalPage) {
      self.setData({
        isEmpty: true,
        scrollHandle: 'scrollHandle1'
      })
      if (self.data.endPage != 0) { //如果最后一页的加载不等于0
        self.setData({
          limitPage: self.data.endPage,
        })
      }
      this.fetchPostsData(self.data);
    } else {
      this.fetchPostsData(self.data);
    }
  },


  //点击刷新
  refresh: function () {
    this.setData({
      postsList: [], //总的活动
      postsShowSwiperList: [], //轮播图显示的活动
      currentPage: 0, //要跳过查询的页数
      limitPage: 3, //首先显示3条数据（之后加载时都增加3条数据，直到再次加载不够3条）
      isEmpty: false, //当前查询出来的数据是否为空
      totalCount: 0, //总活动数量
      endPage: 0, //最后一页加载多少条
      totalPage: 0, //总页数
      curIndex: 0,
      windowHeight1: 0,
      windowWidth1: 0,
    })
    this.onShow();
  },

  // 点击活动进入活动详情页面
  click_activity: function (e) {
    that = this
    let actid = e.currentTarget.dataset.actid;
    let pubid = e.currentTarget.dataset.pubid;
    wx.getSetting({
      success(res) {
        if (res.authSetting['scope.userInfo']) {
          if (!that.buttonClicked) {
            util.buttonClicked(that)
            wx.navigateTo({
              url: "/pages/detail/detail?actid=" + actid + "&pubid=" + pubid
            });
          }
          console.log("if getset", res, "已授权状态")
        } else {
          wx.showModal({
            showCancel: false,
            content: '请先登录',
            success (res) {
              if (res.confirm) {
                that.setData({
                  isLogin: true
                })
              } 
            }
          })
        }
      }
    })
  },
  //点击搜索
  click_search: function () {
    if (!this.buttonClicked) {
      util.buttonClicked(this);
      console.log(getCurrentPages(),3333)
      wx.navigateTo({
        url: '/pages/search/search',
      });
    }
  },


  //关闭登录弹窗
  hideModal: function () {
    this.setData({
      isLogin: false
    })
  },
  //页面触底触发
  onReachBottom: function () {
    console.log(this.data.currentPage + 1, this.data.totalPage, 999)
    if (this.data.currentPage + 1 < this.data.totalPage) {
      setTimeout(() => {
        this.scrollHandle()
      }, 350) //350ms内不能频繁触发
    } else {
      this.scrollHandle1()
    }
  },
  // 封装函数获取ID为box的元素实际高度 
  getScrollHeight: function () {
    wx.createSelectorQuery().select('#box').boundingClientRect((rect) => {
      this.setData({
        scrollHeight: rect.height
      })
      console.log(this.data.scrollHeight, "当前页面高度")
    }).exec()
  },
  //回到顶部
  goTop: function () {
    wx.pageScrollTo({
      scrollTop: 0,
      duration: 300
    })
  },
  //页面滚动触发
  onPageScroll: function (e) {
    // console.log(e.scrollTop)
    //判断回到顶部按钮是否显示
      if (e.scrollTop > 1132) {
        this.setData({
          cangotop: true
        })
      } else {
        this.setData({
          cangotop: false
        })
      }
      if (e.scrollTop <= 0) {
        // 滚动到最顶部
        e.scrollTop = 0;
      } else if (e.scrollTop > this.data.scrollHeight) {
        // 滚动到最底部
        e.scrollTop = this.data.scrollHeight;
      }
      if (e.scrollTop > this.data.scrollTop || e.scrollTop >= this.data.scrollHeight) {
        //向下滚动 
        //  if (e.scrollTop > 400) {
        // this.setData({
        //   showSearch: true
        // })
        //  console.log('向下 ', this.data.scrollHeight)
      } else {
        //向上滚动 
        // this.setData({
        //   showSearch: false
        // })
        //  console.log('向上滚动 ', this.data.scrollHeight)
      }
      //给scrollTop重新赋值 
      this.setData({
        scrollTop: e.scrollTop
      })
    
    
  },
  //下拉刷新触发
  onPullDownRefresh: function (e) {
    this.refresh()
    console.log("7777")
  },
  onShareAppMessage: function () {}
})

//根据活动类型获取活动类型名称
function getTypeName(acttype) {
  var acttypeName = "";
  if (acttype == 1) acttypeName = "运动";
  else if (acttype == 2) acttypeName = "游戏";
  else if (acttype == 3) acttypeName = "交友";
  else if (acttype == 4) acttypeName = "旅行";
  else if (acttype == 5) acttypeName = "读书";
  else if (acttype == 6) acttypeName = "竞赛";
  else if (acttype == 7) acttypeName = "电影";
  else if (acttype == 8) acttypeName = "音乐";
  else if (acttype == 9) acttypeName = "其他";
  return acttypeName;
}